package com.huawei.cloud.phone.management.application.pkg;

import com.huawei.cloud.phone.management.application.pkg.dto.PhoneInfoDTO;
import com.huawei.cloud.phone.management.application.pkg.dto.PkgDTO;
import com.huawei.cloud.phone.management.domain.phone.PhoneDomainService;
import com.huawei.cloud.phone.management.domain.pkg.PkgData;
import com.huawei.cloud.phone.management.domain.pkg.PkgDomainService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Component
public class PkgServiceImpl implements PkgService {
    private final PkgDomainService pkgDomainService;

    private final PhoneDomainService phoneDomainService;


    @Override
    public void installPkg(@NonNull PkgDTO pkgDTO) {
        PkgData pkgData = PkgData.convertPkgData(pkgDTO);
        log.info("pkg data: {}", pkgData);
        List<String> phoneIds = getPhoneIds(pkgDTO.getPhoneInfo());
        pkgDomainService.installPkg(phoneIds, pkgData);
    }

    @Override
    public void installSharePkg(@NonNull PkgDTO pkgDTO) {
        Map<String, Set<String>> serverPhoneIdMap = getServerPhoneMap(pkgDTO.getPhoneInfo());
        PkgData pkgData = PkgData.convertPkgData(pkgDTO);
        log.info("pkg data: {}", pkgData);
        pkgDomainService.installSharePkg(serverPhoneIdMap, pkgData);
    }

    @Override
    public void uninstallPkg(@NonNull PkgDTO pkgDTO) {
        String pkgName = pkgDTO.getApk().getPkgName();
        log.info("pkg data: {}", pkgName);
        List<String> phoneIds = getPhoneIds(pkgDTO.getPhoneInfo());
        pkgDomainService.uninstallPkg(phoneIds, pkgName);
    }

    @Override
    public void uninstallSharePkg(@NonNull PkgDTO pkgDTO) {
        String pkgName = pkgDTO.getApk().getPkgName();
        log.info("pkg data: {}", pkgName);
        List<String> phoneIds = getPhoneIds(pkgDTO.getPhoneInfo());
        pkgDomainService.uninstallSharePkg(phoneIds, pkgName);
    }

    private Map<String, Set<String>> getServerPhoneMap(PhoneInfoDTO phoneInfo) {
        List<String> serverIds = phoneInfo.getServerIds();
        phoneDomainService.checkServerIds(serverIds);
        List<String> phoneIds = phoneInfo.getPhoneIds();
        phoneDomainService.checkPhoneIds(phoneIds);
        return phoneDomainService.getServerAndPhoneIds(serverIds, phoneIds);
    }

    private List<String> getPhoneIds(PhoneInfoDTO phoneInfo) {
        Map<String, Set<String>> serverPhoneMap = getServerPhoneMap(phoneInfo);
        return serverPhoneMap.values().stream().flatMap(Collection::stream).distinct().collect(Collectors.toList());
    }
}
